package Streaming;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import java.util.LinkedList;
import java.util.Vector;
/**
 * a small server running in the background to accept and handle 
 * requests of IWP clients
 */
public class HTTPServer implements Runnable{
	
	private static final int port = 666;
	
	private ServerSocket server;
	private String password;
	private Vector<String> connectedusers;
	
	private LinkedList<ActionListener> listeners;
	
	private boolean running = false;
	
	public HTTPServer(){
		connectedusers = new Vector<String>();
		listeners = new LinkedList<ActionListener>();
	}
	
	@Override
	public void run(){
		
		running = true;
		try {
			server = new ServerSocket(port);
		} catch (IOException e1) {
			// handle
		}
		
		while (running) {
			try {
				Socket socket = server.accept();
				String newUser = new ClientConnector(password, socket).call();

				while(newUser == null){
					Thread.sleep(100);
				}
				
				if (newUser != null && newUser != "x") {
					connectedusers.add(newUser);
					fireNewUserEvent();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}	
	}
	
	public void setPwd(String newPwd){
		password = newPwd;
	}
	
	public Vector<String> getConnectedUsers(){
		return connectedusers;
	}
	
	public void stopServer(){
		this.running = false;
	}
	
	public void kickUser(String user){
		connectedusers.remove(user);
	}
	
	public void addListener(ActionListener listener){
		listeners.add(listener);
	}
	
	private void fireNewUserEvent(){
		for(ActionListener l : listeners){
			l.actionPerformed(new ActionEvent(this,0, "New user connected: " + connectedusers.lastElement().toString()));
		}
	}

}
